'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports ua
Imports System.io

Public Class frmReports
    Inherits System.Windows.Forms.Form

    Private AppDataPath As String = GetAppDataPath()
    Private LogDateArray As New ArrayList
    Private RowId As New ArrayList
    Private NewConfigurationData As New ConfigurationData

    Private DisplayTypeIndex As Integer = 1
    Private FormResizing As Boolean = False
    Private BoldFont As New System.Drawing.Font("Tahoma", 8.25, FontStyle.Bold)
    Private FormInitialising As Boolean = True

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAbout.Click
        Dim frmAbout As New frmAbout
        frmAbout.ShowDialog()
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex > 3 Then Exit Sub
        maketable()
    End Sub

    Private Sub cboMonths_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboMonths.SelectedIndexChanged
        If cboMonths.SelectedIndex < 1 Then
            btnPurge.Enabled = False
        Else
            btnPurge.Enabled = True
        End If
    End Sub

    Sub maketable()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim x As Integer
            Dim RowData(8) As String

            If TabControl1.SelectedIndex = 1 Then
                'clear entries
                dgvDaily.Rows.Clear()

                Application.DoEvents()

                Dim LogDate As Integer                      '4 bytes
                Dim LogHour As Integer                      '1 byte
                Dim ISPPeakDownload As Single               '4 bytes
                Dim ISPPeakUpload As Single                 '4 bytes
                Dim ISPOffpeakDownload As Single             '4 bytes
                Dim ISPOffpeakUpload As Single               '4 bytes

                Dim ISPPeakDownloadTotal(LogDateArray.Count - 1) As Single
                Dim ISPPeakUploadTotal(LogDateArray.Count - 1) As Single
                Dim ISPOffpeakDownloadTotal(LogDateArray.Count - 1) As Single
                Dim ISPOffpeakUploadTotal(LogDateArray.Count - 1) As Single
                Dim ISPPeakDownloadLast(LogDateArray.Count - 1) As String
                Dim ISPPeakUploadLast(LogDateArray.Count - 1) As String
                Dim ISPOffpeakDownloadLast(LogDateArray.Count - 1) As String
                Dim ISPOffpeakUploadLast(LogDateArray.Count - 1) As String
                Dim NICPeakDownloadTotal(LogDateArray.Count - 1) As Single
                Dim NICOffpeakDownloadTotal(LogDateArray.Count - 1) As Single
                Dim NICPeakUploadTotal(LogDateArray.Count - 1) As Single
                Dim NICOffpeakUploadTotal(LogDateArray.Count - 1) As Single

                Dim fsLog As New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
                Dim rLog As New IO.BinaryReader(fsLog)

                'jump to start of last record
                fsLog.Seek(-54, IO.SeekOrigin.End)

                'loop through file 
                While fsLog.Position >= 0
                    'get record data
                    LogDate = rLog.ReadInt32
                    LogHour = rLog.ReadByte

                    'find logdate in index
                    x = LogDateArray.BinarySearch(LogDate)

                    'skip forward
                    fsLog.Seek(9, IO.SeekOrigin.Current)
                    ISPPeakDownload = rLog.ReadSingle
                    ISPPeakUpload = rLog.ReadSingle
                    ISPOffpeakDownload = rLog.ReadSingle
                    ISPOffpeakUpload = rLog.ReadSingle

                    'last ISP entry of day
                    If ISPPeakDownloadLast(x) = "" Then ISPPeakDownloadLast(x) = Format(ISPPeakDownload)
                    If ISPPeakUploadLast(x) = "" Then ISPPeakUploadLast(x) = Format(ISPPeakUpload)
                    If ISPOffpeakDownloadLast(x) = "" Then ISPOffpeakDownloadLast(x) = Format(ISPOffpeakDownload)
                    If ISPOffpeakUploadLast(x) = "" Then ISPOffpeakUploadLast(x) = Format(ISPOffpeakUpload)

                    'skip forward
                    fsLog.Seek(16, IO.SeekOrigin.Current)

                    'sum values
                    Dim bolOffpeakNow As Boolean = False
                    'check if we are in off Peak time
                    If Val(NewConfigurationData.OffpeakStartHour) <> 0 Or Val(NewConfigurationData.OffpeakEndHour) <> 0 Then
                        If LogHour >= Val(NewConfigurationData.OffpeakStartHour) And LogHour < Val(NewConfigurationData.OffpeakEndHour) Then
                            If Val(NewConfigurationData.OffpeakUsageLimit) = 0 Then
                                bolOffpeakNow = True
                            Else
                                If ISPOffpeakDownload < Val(NewConfigurationData.OffpeakUsageLimit) Then
                                    bolOffpeakNow = True
                                Else
                                    bolOffpeakNow = False
                                End If
                            End If
                        Else
                            bolOffpeakNow = False
                        End If
                    End If

                    'check if we are in Peak or off Peak time
                    If bolOffpeakNow = True Then
                        'Offpeak
                        NICOffpeakDownloadTotal(x) += rLog.ReadSingle
                        NICOffpeakUploadTotal(x) += rLog.ReadSingle
                    Else
                        'Peak
                        NICPeakDownloadTotal(x) += rLog.ReadSingle
                        NICPeakUploadTotal(x) += rLog.ReadSingle
                    End If

                    'jump to start of previous record
                    'check for eof
                    If fsLog.Position < 108 Then
                        Exit While
                    Else
                        fsLog.Seek(-108, IO.SeekOrigin.Current)
                    End If
                End While

                rLog.Close()
                fsLog.Close()

                '#########################################

                dgvDaily.SuspendLayout()

                'loop through array and write each day to a row
                For x = LogDateArray.Count - 1 To 0 Step -1
                    RowData(0) = Format(Date.ParseExact(LogDateArray(x).ToString, "yyyyMMdd", Nothing), "")

                    'if first day of month then first entry of day = 0
                    If Microsoft.VisualBasic.Right(LogDateArray(x).ToString, 2) = "01" Or x = 0 Then
                        ISPPeakDownloadTotal(x) = CSng(ISPPeakDownloadLast(x))
                        ISPPeakUploadTotal(x) = CSng(ISPPeakUploadLast(x))
                        ISPOffpeakDownloadTotal(x) = CSng(ISPOffpeakDownloadLast(x))
                        ISPOffpeakUploadTotal(x) = CSng(ISPOffpeakUploadLast(x))
                    Else
                        'get last entry of previous day
                        ISPPeakDownloadTotal(x) = CSng(Val(ISPPeakDownloadLast(x)) - Val(ISPPeakDownloadLast(x - 1)))
                        ISPPeakUploadTotal(x) = CSng(Val(ISPPeakUploadLast(x)) - Val(ISPPeakUploadLast(x - 1)))
                        ISPOffpeakDownloadTotal(x) = CSng(Val(ISPOffpeakDownloadLast(x)) - Val(ISPOffpeakDownloadLast(x - 1)))
                        ISPOffpeakUploadTotal(x) = CSng(Val(ISPOffpeakUploadLast(x)) - Val(ISPOffpeakUploadLast(x - 1)))
                    End If

                    RowData(1) = ISPPeakDownloadTotal(x) & " MB"
                    RowData(2) = ISPPeakUploadTotal(x) & " MB"
                    RowData(3) = Format(NICPeakDownloadTotal(x) / 1024, "0.00") & " MB"
                    RowData(4) = Format(NICPeakUploadTotal(x) / 1024, "0.00") & " MB"
                    RowData(5) = ISPOffpeakDownloadTotal(x) & " MB"
                    RowData(6) = ISPOffpeakUploadTotal(x) & " MB"
                    RowData(7) = Format(NICOffpeakDownloadTotal(x) / 1024, "0.00") & " MB"
                    RowData(8) = Format(NICOffpeakUploadTotal(x) / 1024, "0.00") & " MB"
                    dgvDaily.Rows.Add(RowData)
                    If UnixDetected() = False Then
                        dgvDaily.Rows(dgvDaily.Rows.Count - 1).Cells.Item(0).Style.Font = BoldFont
                    End If
                Next

                'make blank line
                RowData(0) = ""
                RowData(1) = ""
                RowData(2) = ""
                RowData(3) = ""
                RowData(4) = ""
                RowData(5) = ""
                RowData(6) = ""
                RowData(7) = ""
                RowData(8) = ""
                dgvDaily.Rows.Add(RowData)

                'make totals 
                RowData(0) = "Totals"

                Dim TotalISPPeakDownload As Single
                Dim TotalISPPeakUpload As Single
                Dim TotalISPOffpeakDownload As Single
                Dim TotalISPOffpeakUpload As Single
                Dim TotalNICPeakDownload As Single
                Dim TotalNICPeakUpload As Single
                Dim TotalNICOffpeakDownload As Single
                Dim TotalNICOffpeakUpload As Single

                For x = 0 To LogDateArray.Count - 1
                    TotalISPPeakDownload += ISPPeakDownloadTotal(x)
                    TotalISPPeakUpload += ISPPeakUploadTotal(x)
                    TotalNICPeakDownload += NICPeakDownloadTotal(x)
                    TotalNICPeakUpload += NICPeakUploadTotal(x)
                    TotalISPOffpeakDownload += ISPOffpeakDownloadTotal(x)
                    TotalISPOffpeakUpload += ISPOffpeakUploadTotal(x)
                    TotalNICOffpeakDownload += NICOffpeakDownloadTotal(x)
                    TotalNICOffpeakUpload += NICOffpeakUploadTotal(x)
                Next

                RowData(1) = TotalISPPeakDownload & " MB"
                RowData(2) = TotalISPPeakUpload & " MB"
                RowData(3) = Format(TotalNICPeakDownload / 1024, "0.00") & " MB"
                RowData(4) = Format(TotalNICPeakUpload / 1024, "0.00") & " MB"
                RowData(5) = TotalISPOffpeakDownload & " MB"
                RowData(6) = TotalISPOffpeakUpload & " MB"
                RowData(7) = Format(TotalNICOffpeakDownload / 1024, "0.00") & " MB"
                RowData(8) = Format(TotalNICOffpeakUpload / 1024, "0.00") & " MB"
                dgvDaily.Rows.Add(RowData)
                For x = 0 To 8
                    If UnixDetected() = False Then
                        dgvDaily.Rows(dgvDaily.Rows.Count - 1).Cells.Item(x).Style.Font = BoldFont
                    End If
                Next

                dgvDaily.ResumeLayout()
                dgvDaily.Invalidate()

                '###########################################

            ElseIf TabControl1.SelectedIndex = 2 Then
                'clear entries
                dgvMonthly.Rows.Clear()

                Application.DoEvents()

                Dim LogMonthArray As New ArrayList
                Dim YearMonth As String = ""
                Dim LastYearMonth As String = ""

                'get unique months
                For x = 0 To LogDateArray.Count - 1
                    YearMonth = Microsoft.VisualBasic.Left(LogDateArray(x).ToString, 6)
                    If x = 0 Then
                        LogMonthArray.Add(YearMonth)
                    Else
                        If YearMonth <> LastYearMonth Then LogMonthArray.Add(YearMonth)
                    End If
                    LastYearMonth = YearMonth
                Next

                'check last record
                If LogMonthArray.Count > 0 And YearMonth <> LastYearMonth Then
                    'add entry
                    LogDateArray.Add(YearMonth)
                End If

                Dim LogDate As String                       '4 bytes
                Dim LogHour As Integer                      '1 byte
                Dim ISPPeakDownload As Single                      '4 bytes
                Dim ISPPeakUpload As Single                      '4 bytes
                Dim ISPOffpeakDownload As Single               '4 bytes
                Dim ISPOffpeakUpload As Single               '4 bytes
                Dim ISPPeakDownloadLast(LogMonthArray.Count - 1) As String
                Dim ISPPeakUploadLast(LogMonthArray.Count - 1) As String
                Dim NICPeakDownloadTotal(LogMonthArray.Count - 1) As Single
                Dim NICPeakUploadTotal(LogMonthArray.Count - 1) As Single
                Dim ISPOffpeakDownloadLast(LogMonthArray.Count - 1) As String
                Dim ISPOffpeakUploadLast(LogMonthArray.Count - 1) As String
                Dim NICOffpeakDownloadTotal(LogMonthArray.Count - 1) As Single
                Dim NICOffpeakUploadTotal(LogMonthArray.Count - 1) As Single

                Dim fsLog As New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
                Dim rLog As New IO.BinaryReader(fsLog)

                'jump to start of last record
                fsLog.Seek(-54, IO.SeekOrigin.End)

                'loop through file 
                While fsLog.Position >= 0
                    'get record data
                    LogDate = Microsoft.VisualBasic.Left(rLog.ReadInt32.ToString, 6)
                    LogHour = rLog.ReadByte

                    'find logdate in index
                    x = LogMonthArray.BinarySearch(LogDate)

                    'skip forward
                    fsLog.Seek(9, IO.SeekOrigin.Current)
                    ISPPeakDownload = rLog.ReadSingle
                    ISPPeakUpload = rLog.ReadSingle
                    ISPOffpeakDownload = rLog.ReadSingle
                    ISPOffpeakUpload = rLog.ReadSingle

                    'last ISP entry of month
                    If ISPPeakDownloadLast(x) = "" Then ISPPeakDownloadLast(x) = Format(ISPPeakDownload)
                    If ISPPeakUploadLast(x) = "" Then ISPPeakUploadLast(x) = Format(ISPPeakUpload)
                    If ISPOffpeakDownloadLast(x) = "" Then ISPOffpeakDownloadLast(x) = Format(ISPOffpeakDownload)
                    If ISPOffpeakUploadLast(x) = "" Then ISPOffpeakUploadLast(x) = Format(ISPOffpeakUpload)

                    'skip forward
                    fsLog.Seek(16, IO.SeekOrigin.Current)

                    'sum values
                    Dim bolOffpeakNow As Boolean = False
                    'check if we are in off Peak time
                    If Val(NewConfigurationData.OffpeakStartHour) <> 0 Or Val(NewConfigurationData.OffpeakEndHour) <> 0 Then
                        If LogHour >= Val(NewConfigurationData.OffpeakStartHour) And LogHour < Val(NewConfigurationData.OffpeakEndHour) Then
                            If Val(NewConfigurationData.OffpeakUsageLimit) = 0 Then
                                bolOffpeakNow = True
                            Else
                                If ISPOffpeakDownload < Val(NewConfigurationData.OffpeakUsageLimit) Then
                                    bolOffpeakNow = True
                                Else
                                    bolOffpeakNow = False
                                End If
                            End If
                        Else
                            bolOffpeakNow = False
                        End If
                    End If

                    If bolOffpeakNow = True Then
                        'Offpeak
                        NICOffpeakDownloadTotal(x) += rLog.ReadSingle
                        NICOffpeakUploadTotal(x) += rLog.ReadSingle
                    Else
                        'Peak
                        NICPeakDownloadTotal(x) += rLog.ReadSingle
                        NICPeakUploadTotal(x) += rLog.ReadSingle
                    End If

                    'jump to start of previous record
                    'check for eof
                    If fsLog.Position < 108 Then
                        Exit While
                    Else
                        fsLog.Seek(-108, IO.SeekOrigin.Current)
                    End If
                End While

                rLog.Close()
                fsLog.Close()

                '#########################################

                dgvMonthly.SuspendLayout()

                'clear entries
                dgvMonthly.Rows.Clear()

                'loop through array and write each day to a row
                For x = LogMonthArray.Count - 1 To 0 Step -1
                    RowData(0) = Format(CDate("1/" & Mid(LogMonthArray(x).ToString, 5, 2) & "/" & Microsoft.VisualBasic.Left(LogMonthArray(x).ToString, 4)), "MMM yyyy")
                    RowData(1) = ISPPeakDownloadLast(x) & " MB"
                    RowData(2) = ISPPeakUploadLast(x) & " MB"
                    RowData(3) = Format(NICPeakDownloadTotal(x) / 1024, "0.00") & " MB"
                    RowData(4) = Format(NICPeakUploadTotal(x) / 1024, "0.00") & " MB"
                    RowData(5) = ISPOffpeakDownloadLast(x) & " MB"
                    RowData(6) = ISPOffpeakUploadLast(x) & " MB"
                    RowData(7) = Format(NICOffpeakDownloadTotal(x) / 1024, "0.00") & " MB"
                    RowData(8) = Format(NICOffpeakUploadTotal(x) / 1024, "0.00") & " MB"
                    dgvMonthly.Rows.Add(RowData)
                    If UnixDetected() = False Then
                        dgvMonthly.Rows(dgvMonthly.Rows.Count - 1).Cells.Item(0).Style.Font = BoldFont
                    End If
                Next

                'make blank line
                RowData(0) = ""
                RowData(1) = ""
                RowData(2) = ""
                RowData(3) = ""
                RowData(4) = ""
                RowData(5) = ""
                RowData(6) = ""
                RowData(7) = ""
                RowData(8) = ""
                dgvMonthly.Rows.Add(RowData)

                'make totals 
                RowData(0) = "Totals"

                Dim TotalISPPeakDownload As Single
                Dim TotalISPPeakUpload As Single
                Dim TotalISPOffpeakDownload As Single
                Dim TotalISPOffpeakUpload As Single
                Dim TotalNICPeakDownload As Single
                Dim TotalNICPeakUpload As Single
                Dim TotalNICOffpeakDownload As Single
                Dim TotalNICOffpeakUpload As Single

                For x = 0 To LogMonthArray.Count - 1
                    TotalISPPeakDownload = CSng(TotalISPPeakDownload + CDbl(ISPPeakDownloadLast(x)))
                    TotalISPPeakUpload = CSng(TotalISPPeakUpload + CDbl(ISPPeakUploadLast(x)))
                    TotalNICPeakDownload = TotalNICPeakDownload + NICPeakDownloadTotal(x)
                    TotalNICPeakUpload += NICPeakUploadTotal(x)
                    TotalISPOffpeakDownload = CSng(TotalISPOffpeakDownload + CDbl(ISPOffpeakDownloadLast(x)))
                    TotalISPOffpeakUpload = CSng(TotalISPOffpeakUpload + CDbl(ISPOffpeakUploadLast(x)))
                    TotalNICOffpeakDownload += NICOffpeakDownloadTotal(x)
                    TotalNICOffpeakUpload += NICOffpeakUploadTotal(x)
                Next

                RowData(1) = TotalISPPeakDownload & " MB"
                RowData(2) = TotalISPPeakUpload & " MB"
                RowData(3) = Format(TotalNICPeakDownload / 1024, "0.00") & " MB"
                RowData(4) = Format(TotalNICPeakUpload / 1024, "0.00") & " MB"
                RowData(5) = TotalISPOffpeakDownload & " MB"
                RowData(6) = TotalISPOffpeakUpload & " MB"
                RowData(7) = Format(TotalNICOffpeakDownload / 1024, "0.00") & " MB"
                RowData(8) = Format(TotalNICOffpeakUpload / 1024, "0.00") & " MB"
                dgvMonthly.Rows.Add(RowData)
                For x = 0 To 8
                    If UnixDetected() = False Then
                        dgvMonthly.Rows(dgvMonthly.Rows.Count - 1).Cells.Item(x).Style.Font = BoldFont
                    End If
                Next

                dgvMonthly.ResumeLayout()
                dgvMonthly.Invalidate()
            End If
        Catch ex As Exception
            FileClose()
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub cboDate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboDate.SelectedIndexChanged
        RefreshDetailed()
    End Sub

    Public Sub RefreshDetailed()
        Try
            'clear entries
            dgvDetailed.Rows.Clear()
            Me.Cursor = Cursors.WaitCursor
            FormInitialising = True

            Application.DoEvents()

            Dim FirstISPPeakDownload As Double
            Dim FirstISPPeakUpload As Double
            Dim LastISPPeakDownload As Double
            Dim LastISPPeakUpload As Double
            Dim FirstISPOffpeakDownload As Double
            Dim FirstISPOffpeakUpload As Double
            Dim LastISPOffpeakDownload As Double
            Dim LastISPOffpeakUpload As Double
            Dim NICPeakDownloadTotal As Double
            Dim NICOffpeakDownloadTotal As Double
            Dim NICPeakUploadTotal As Double
            Dim NICOffpeakUploadTotal As Double
            Dim Counter, RecordCount As Integer

            Dim LogDate As Integer                      '4 bytes
            Dim LogHour As Byte                         '1 byte
            Dim LogMinute As Byte                       '1 byte
            Dim LogSecond As Byte                       '1 byte
            Dim ISPDate As Integer                      '4 bytes
            Dim ISPHour As Byte                         '1 byte
            Dim ISPMinute As Byte                       '1 byte
            Dim ISPSecond As Byte                       '1 byte
            Dim ISPPeakDownload As Single               '4 bytes
            Dim ISPPeakUpload As Single                 '4 bytes
            Dim ISPOffpeakDownload As Single            '4 bytes
            Dim ISPOffpeakUpload As Single              '4 bytes
            Dim DownloadRaw As Double                   '8 bytes
            Dim UploadRaw As Double                     '8 bytes
            Dim DownloadChange As Single                '4 bytes
            Dim UploadChange As Single                  '4 bytes
            Dim fsLog As IO.FileStream
            Dim rLog As IO.BinaryReader
            Dim SelectedDate As Integer = CInt(Format(CDate(cboDate.Text), "yyyyMMdd"))
            Dim LastValuePreviousDayDate As Integer = CInt(Format(CDate(cboDate.Text).AddDays(-1), "yyyyMMdd"))
            Dim LastValuePreviousDayFound As Boolean = False
            Dim LastValuePreviousDayLogHour As Byte
            Dim LastValuePreviousDayLogMinute As Byte
            Dim LastValuePreviousDayLogSecond As Byte
            Dim LastValuePreviousDayISPHour As Byte
            Dim LastValuePreviousDayISPMinute As Byte
            Dim LastValuePreviousDayISPSecond As Byte
            Dim LastValuePreviousDayISPPeakDownload As Single
            Dim LastValuePreviousDayISPPeakUpload As Single
            Dim LastValuePreviousDayISPOffpeakDownload As Single
            Dim LastValuePreviousDayISPOffpeakUpload As Single
            Dim RowData(9) As String

            fsLog = New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
            rLog = New IO.BinaryReader(fsLog)

            dgvDetailed.SuspendLayout()

            RowId.Clear()

            'jump to start of last record
            fsLog.Seek(-54, IO.SeekOrigin.End)

            'loop backward through file 
            While fsLog.Position >= 0

                'get record date
                LogDate = rLog.ReadInt32
                RecordCount += 1
                'look for where LogDate = cboDate.Text
                If LogDate = SelectedDate Then
                    LogHour = rLog.ReadByte
                    LogMinute = rLog.ReadByte
                    LogSecond = rLog.ReadByte
                    ISPDate = rLog.ReadInt32
                    ISPHour = rLog.ReadByte
                    ISPMinute = rLog.ReadByte
                    ISPSecond = rLog.ReadByte
                    ISPPeakDownload = rLog.ReadSingle
                    ISPPeakUpload = rLog.ReadSingle
                    ISPOffpeakDownload = rLog.ReadSingle
                    ISPOffpeakUpload = rLog.ReadSingle
                    DownloadRaw = rLog.ReadDouble
                    UploadRaw = rLog.ReadDouble
                    DownloadChange = rLog.ReadSingle
                    UploadChange = rLog.ReadSingle

                    RowId.Add(RecordCount)

                    RowData(0) = Format(LogHour, "00") & ":" & Format(LogMinute, "00") & ":" & Format(LogSecond, "00")
                    RowData(1) = Format(ISPHour, "00") & ":" & Format(ISPMinute, "00") & ":" & Format(ISPSecond, "00")

                    Dim bolOffpeakNow As Boolean = False
                    'check if we are in off Peak time
                    If Val(NewConfigurationData.OffpeakStartHour) <> 0 Or Val(NewConfigurationData.OffpeakEndHour) <> 0 Then
                        If LogHour >= Val(NewConfigurationData.OffpeakStartHour) And LogHour < Val(NewConfigurationData.OffpeakEndHour) Then
                            If Val(NewConfigurationData.OffpeakUsageLimit) = 0 Then
                                bolOffpeakNow = True
                            Else
                                If ISPOffpeakDownload < Val(NewConfigurationData.OffpeakUsageLimit) Then
                                    bolOffpeakNow = True
                                Else
                                    bolOffpeakNow = False
                                End If
                            End If
                        Else
                            bolOffpeakNow = False
                        End If
                    End If

                    'check if we are in Peak or off Peak time
                    If bolOffpeakNow = True Then
                        'Offpeak
                        RowData(4) = "-"
                        RowData(5) = "-"
                        RowData(8) = Format(DownloadChange / 1024, "0.00") & " MB"
                        RowData(9) = Format(UploadChange / 1024, "0.00") & " MB"
                        NICOffpeakDownloadTotal += DownloadChange
                        NICOffpeakUploadTotal += UploadChange
                    Else
                        'Peak
                        RowData(4) = Format(DownloadChange / 1024, "0.00") & " MB"
                        RowData(5) = Format(UploadChange / 1024, "0.00") & " MB"
                        RowData(8) = "-"
                        RowData(9) = "-"
                        NICPeakDownloadTotal += DownloadChange
                        NICPeakUploadTotal += UploadChange
                    End If

                    Counter += 1
                    If Counter = 1 Then
                        LastISPPeakDownload = ISPPeakDownload
                        LastISPPeakUpload = ISPPeakUpload
                        LastISPOffpeakDownload = ISPOffpeakDownload
                        LastISPOffpeakUpload = ISPOffpeakUpload
                    End If
                    RowData(2) = ISPPeakDownload & " MB"
                    RowData(3) = ISPPeakUpload & " MB"
                    RowData(6) = ISPOffpeakDownload & " MB"
                    RowData(7) = ISPOffpeakUpload & " MB"

                    FirstISPPeakDownload = ISPPeakDownload
                    FirstISPPeakUpload = ISPPeakUpload
                    FirstISPOffpeakDownload = ISPOffpeakDownload
                    FirstISPOffpeakUpload = ISPOffpeakUpload

                    dgvDetailed.Rows.Add(RowData)

                    'set font
                    If UnixDetected() = False Then
                        dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(0).Style.Font = BoldFont
                    End If

                    'if "-" then set to readonly
                    If bolOffpeakNow = True Then
                        'Offpeak
                        dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(4).ReadOnly = True
                        dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(5).ReadOnly = True
                    Else
                        'Peak
                        dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(8).ReadOnly = True
                        dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(9).ReadOnly = True
                    End If

                    'jump to start of previous record
                    'check for eof
                    If fsLog.Position < 108 Then
                        Exit While
                    Else
                        fsLog.Seek(-108, IO.SeekOrigin.Current)
                    End If
                ElseIf LastValuePreviousDayFound = False And LogDate = LastValuePreviousDayDate Then
                    LastValuePreviousDayFound = True
                    LastValuePreviousDayLogHour = rLog.ReadByte
                    LastValuePreviousDayLogMinute = rLog.ReadByte
                    LastValuePreviousDayLogSecond = rLog.ReadByte
                    'skip date
                    rLog.ReadInt32()
                    LastValuePreviousDayISPHour = rLog.ReadByte
                    LastValuePreviousDayISPMinute = rLog.ReadByte
                    LastValuePreviousDayISPSecond = rLog.ReadByte
                    LastValuePreviousDayISPPeakDownload = rLog.ReadSingle
                    LastValuePreviousDayISPPeakUpload = rLog.ReadSingle
                    LastValuePreviousDayISPOffpeakDownload = rLog.ReadSingle
                    LastValuePreviousDayISPOffpeakUpload = rLog.ReadSingle

                    Exit While
                Else
                    'skip to start of previous record
                    If fsLog.Position < 58 Then
                        Exit While
                    Else
                        fsLog.Seek(-58, IO.SeekOrigin.Current)
                    End If
                End If
            End While

            rLog.Close()
            fsLog.Close()

            If Format(CDate(cboDate.Text), "dd") = "01" Then
                FirstISPPeakDownload = 0
            Else
                'get last value of previous day
                RowData(0) = Format(LastValuePreviousDayLogHour, "00") & ":" & Format(LastValuePreviousDayLogMinute, "00") & ":" & Format(LastValuePreviousDayLogSecond, "00")
                RowData(1) = Format(LastValuePreviousDayISPHour, "00") & ":" & Format(LastValuePreviousDayISPMinute, "00") & ":" & Format(LastValuePreviousDayISPSecond, "00")
                RowData(2) = LastValuePreviousDayISPPeakDownload & " MB"
                FirstISPPeakDownload = LastValuePreviousDayISPPeakDownload
                RowData(3) = LastValuePreviousDayISPPeakUpload & " MB"
                FirstISPPeakUpload = LastValuePreviousDayISPPeakUpload
                RowData(4) = "-"
                RowData(5) = "-"
                RowData(6) = LastValuePreviousDayISPOffpeakDownload & " MB"
                FirstISPOffpeakDownload = LastValuePreviousDayISPOffpeakDownload
                RowData(7) = LastValuePreviousDayISPOffpeakUpload & " MB"
                FirstISPOffpeakUpload = LastValuePreviousDayISPOffpeakUpload
                RowData(8) = "-"
                RowData(9) = "-"
                dgvDetailed.Rows.Add(RowData)
                dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).ReadOnly = True
                If UnixDetected() = False Then
                    dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(0).Style.Font = BoldFont
                End If
            End If
            'MessageBox.Show("got here")

            'make blank line
            RowData(0) = ""
            RowData(1) = ""
            RowData(2) = ""
            RowData(3) = ""
            RowData(4) = ""
            RowData(5) = ""
            RowData(6) = ""
            RowData(7) = ""
            RowData(8) = ""
            RowData(9) = ""
            dgvDetailed.Rows.Add(RowData)
            dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).ReadOnly = True

            'make totals
            RowData(0) = "Totals"
            RowData(1) = cboDate.Text
            RowData(2) = Format(LastISPPeakDownload - FirstISPPeakDownload, "0.00") & " MB"
            RowData(3) = Format(LastISPPeakUpload - FirstISPPeakUpload, "0.00") & " MB"
            RowData(4) = Format(NICPeakDownloadTotal / 1024, "0.00") & " MB"
            RowData(5) = Format(NICPeakUploadTotal / 1024, "0.00") & " MB"
            RowData(6) = Format(LastISPOffpeakDownload - FirstISPOffpeakDownload, "0.00") & " MB"
            RowData(7) = Format(LastISPOffpeakUpload - FirstISPOffpeakUpload, "0.00") & " MB"
            RowData(8) = Format(NICOffpeakDownloadTotal / 1024, "0.00") & " MB"
            RowData(9) = Format(NICOffpeakUploadTotal / 1024, "0.00") & " MB"
            dgvDetailed.Rows.Add(RowData)
            dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).ReadOnly = True

            For x As Integer = 0 To 9
                If UnixDetected() = False Then
                    dgvDetailed.Rows(dgvDetailed.Rows.Count - 1).Cells.Item(x).Style.Font = BoldFont
                End If
            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            dgvDetailed.ResumeLayout()
            dgvDetailed.Invalidate()
            Me.Cursor = Cursors.Default
            FormInitialising = False
        End Try
    End Sub

    Sub GetUniqueLogDate()
        Dim LogDate, LastLogDate As Integer
        Dim TempLogDateArray As New ArrayList
        Dim x As Integer

        Dim fsLog As IO.FileStream
        Dim rLog As IO.BinaryReader

        fsLog = New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite)
        rLog = New IO.BinaryReader(fsLog)

        'loop through file 
        While fsLog.Position < fsLog.Length
            'get record date
            LogDate = rLog.ReadInt32
            If x = 0 Then
                'add entry to array
                TempLogDateArray.Add(LogDate)
            Else
                'look for where LogDate is new
                If LogDate <> LastLogDate Then
                    'add entry to array
                    TempLogDateArray.Add(LogDate)
                End If
            End If

            LastLogDate = LogDate

            'skip to start of next record
            fsLog.Seek(50, IO.SeekOrigin.Current)
            x += 1
        End While

        'check last record
        If x > 1 And LogDate <> LastLogDate Then
            'add entry to array
            TempLogDateArray.Add(LogDate)
        End If

        rLog.Close()
        fsLog.Close()

        'sort array
        TempLogDateArray.Sort()

        'clear
        LogDateArray.Clear()

        'loop through all entries and add unique to arraylist
        LogDate = 0
        LastLogDate = 0
        For x = TempLogDateArray.Count - 1 To 0 Step -1
            LogDate = CInt(TempLogDateArray(x))
            If x = TempLogDateArray.Count - 1 Then
                LogDateArray.Add(LogDate)
            Else
                If LogDate <> LastLogDate Then LogDateArray.Add(LogDate)
            End If
            LastLogDate = LogDate
        Next

        'check last record
        If TempLogDateArray.Count > 0 And LogDate <> LastLogDate Then
            'add entry
            LogDateArray.Add(LogDate)
        End If

        'sort array
        LogDateArray.Sort()

    End Sub

    Private Sub frmReports_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'already running, exit
        Dim myProcesses As Process() = Process.GetProcessesByName("UAReports")
        If myProcesses.Length > 1 Then End
        myProcesses = Nothing

        Try
            'check that the necessary files exist
            If Dir(AppDataPath & "usageagent.log") = "" Then
                MessageBox.Show("Cannot find usageagent.log. UATrayIcon, UAWallpaper or UAImage must be run first before logs can be reviewed.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                End
            End If

            If Dir(AppDataPath & "usageagent.cfg") = "" Then
                MessageBox.Show("Cannot find usageagent.cfg. UATrayIcon, UAWallpaper or UAImage must be run first before logs can be reviewed.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                End
            End If

            'load config
            LoadConfiguration(NewConfigurationData)

            cboMonths.Items.Add("")
            cboMonths.Items.Add("Now")
            cboMonths.Items.Add("This Month")
            cboMonths.Items.Add("Last Month")
            cboMonths.Items.Add("6 Months")
            cboMonths.Items.Add("12 Months")

            'get unique days
            GetUniqueLogDate()

            'loop through all entries and populate date combo
            cboDate.Items.Clear()
            Dim x As Integer
            For x = LogDateArray.Count - 1 To 0 Step -1
                cboDate.Items.Add(Format(Date.ParseExact(LogDateArray(x).ToString, "yyyyMMdd", Nothing), ""))
            Next

            If cboDate.Items.Count > 0 Then cboDate.SelectedIndex = 0
            
            dgvDetailed.ColumnHeadersDefaultCellStyle.Font = BoldFont
            dgvDaily.ColumnHeadersDefaultCellStyle.Font = BoldFont
            dgvMonthly.ColumnHeadersDefaultCellStyle.Font = BoldFont

            maketable()

        Catch ex1 As UnauthorizedAccessException
            MessageBox.Show("Cannot lock the Log file. Please try again.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub btnPurge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPurge.Click
        If MessageBox.Show("Are you sure you want to clear all records older than " & cboMonths.Text & "?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then Exit Sub

        Try
            If cboMonths.SelectedIndex = 1 Then
                'now. delete file
                Kill(AppDataPath & "usageagent.log")

                MessageBox.Show("Records Deleted!" & vbCrLf & vbCrLf & "As there are no records, UAReports will now close. Please restart once the logfile has been re-created.", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End
            Else
                Dim DeleteDate As Date = Date.ParseExact(DateTime.Now.Year & Format(DateTime.Now.Month, "00") & "01", "yyyyMMdd", Nothing)
                If cboMonths.SelectedIndex = 2 Then
                    'this month (do nothing)
                ElseIf cboMonths.SelectedIndex = 3 Then
                    'last month
                    DeleteDate = DeleteDate.AddMonths(-1)
                ElseIf cboMonths.SelectedIndex = 4 Then
                    'six months
                    DeleteDate = DeleteDate.AddMonths(-5)
                ElseIf cboMonths.SelectedIndex = 5 Then
                    '1 year
                    DeleteDate = DeleteDate.AddMonths(-11)
                End If

                Dim LogDate As Integer
                Dim SelectedDate As Integer = CInt(Format(DeleteDate, "yyyyMM01"))
                Dim fsLog As New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite)
                Dim rLog As New IO.BinaryReader(fsLog)
                Dim fsNewLog As New IO.FileStream(AppDataPath & "usageagent_temp.log", IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite)
                Dim wNewLog As New IO.BinaryWriter(fsNewLog)

                'loop through file 
                While fsLog.Position < fsLog.Length
                    'get record date
                    LogDate = rLog.ReadInt32
                    'look for where LogDate > deletedate
                    If LogDate >= SelectedDate Then
                        'write new log file
                        wNewLog.Write(LogDate)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadInt32)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadByte)
                        wNewLog.Write(rLog.ReadSingle)
                        wNewLog.Write(rLog.ReadSingle)
                        wNewLog.Write(rLog.ReadSingle)
                        wNewLog.Write(rLog.ReadSingle)
                        wNewLog.Write(rLog.ReadDouble)
                        wNewLog.Write(rLog.ReadDouble)
                        wNewLog.Write(rLog.ReadSingle)
                        wNewLog.Write(rLog.ReadSingle)
                    Else
                        'skip to start of next record
                        fsLog.Seek(50, IO.SeekOrigin.Current)
                    End If
                End While

                rLog.Close()
                fsLog.Close()
                fsNewLog.Close()
                wNewLog.Close()

                'overwrite log file
                FileCopy(AppDataPath & "usageagent_temp.log", AppDataPath & "usageagent.log")

                'kill old log file
                Kill(AppDataPath & "usageagent_temp.log")

                'get unique days
                GetUniqueLogDate()

                'loop through all entries and populate date combo
                cboDate.Items.Clear()
                Dim x As Integer
                For x = LogDateArray.Count - 1 To 0 Step -1
                    cboDate.Items.Add(Microsoft.VisualBasic.Right(LogDateArray(x).ToString, 2) & "/" & Mid(LogDateArray(x).ToString, 5, 2) & "/" & Microsoft.VisualBasic.Left(LogDateArray(x).ToString, 4))
                Next
                If cboDate.Items.Count > 0 Then cboDate.SelectedIndex = 0
                cboDate.Refresh()
                MessageBox.Show("Records Deleted!", "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub

    Private Sub dgvDetailed_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgvDetailed.SelectionChanged
        If dgvDetailed.SelectedCells.Count > 0 Then
            If dgvDetailed.SelectedCells(0).RowIndex >= 0 And dgvDetailed.SelectedCells(0).RowIndex < dgvDetailed.Rows.Count - 3 Then
                btnDelete.Enabled = True
            Else
                btnDelete.Enabled = False
            End If
        Else
            btnDelete.Enabled = False
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If dgvDetailed.CurrentCell.RowIndex > dgvDetailed.Rows.Count - 2 Then Exit Sub

        Try
            If UnixDetected() = True Then
                'redo check for mono
                If dgvDetailed.SelectedCells.Count > 0 Then
                    If dgvDetailed.SelectedCells(0).RowIndex >= 0 And dgvDetailed.SelectedCells(0).RowIndex < dgvDetailed.Rows.Count - 3 Then
                    Else
                        Exit Sub
                    End If
                Else
                    Exit Sub
                End If
            End If

            Dim SelectedRowIndex As Integer = dgvDetailed.CurrentCell.RowIndex

            dgvDetailed.SelectionMode = DataGridViewSelectionMode.FullRowSelect
            dgvDetailed.Rows.Item(SelectedRowIndex).Selected = True

            If MessageBox.Show("Are you sure you want to delete this row?", "Usage Agent", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then Exit Sub

            'get offset from end
            Dim usage_id As Integer = CInt(RowId(SelectedRowIndex))

            Dim SaveRowIndex As Integer = SelectedRowIndex

            Try
                'source
                Dim fsLog As New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite)
                Dim rLog As New IO.BinaryReader(fsLog)

                'target
                Dim fsNewLog As New IO.FileStream(AppDataPath & "usageagent_temp.log", IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.Write)
                Dim wLog As New IO.BinaryWriter(fsNewLog)

                Dim StartOffset As Integer = CInt(fsLog.Length - (54 * usage_id))

                'copy contents of log file up to start of selected record
                wLog.Write(rLog.ReadBytes(StartOffset))

                'jump to next record
                fsLog.Seek(54, IO.SeekOrigin.Current)

                'copy contents of log file from start of next record to eof
                wLog.Write(rLog.ReadBytes(CInt(fsLog.Length - (StartOffset - 54))))

                rLog.Close()
                wLog.Close()
                fsLog.Close()

                'overwrite log file
                FileCopy(AppDataPath & "usageagent_temp.log", AppDataPath & "usageagent.log")

                'kill old log file
                Kill(AppDataPath & "usageagent_temp.log")

            Catch ex As Exception
                MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try

            RefreshDetailed()

            'jump back to record and highlight
            dgvDetailed.SelectionMode = DataGridViewSelectionMode.CellSelect
            dgvDetailed.Rows.Item(SaveRowIndex).Selected = True

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            dgvDetailed.SelectionMode = DataGridViewSelectionMode.CellSelect
        End Try

    End Sub

    Private Sub dgvDetailed_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDetailed.CellValueChanged
        If FormInitialising = True Then Exit Sub
        If UnixDetected() = True Then Exit Sub

        If e.RowIndex > dgvDetailed.Rows.Count - 2 Then Exit Sub

        Try
            Dim UsageID As Integer = CInt(RowId(e.RowIndex))
            Dim CurrentRowIndex As Integer = e.RowIndex

            Dim ISPPeakDownload As Single
            Dim ISPPeakUpload As Single
            Dim ISPOffpeakDownload As Single
            Dim ISPOffpeakUpload As Single
            Dim NICDownload As Single
            Dim NICUpload As Single

            ISPPeakDownload = CSng(Val(CType(dgvDetailed.Item(2, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))
            ISPPeakUpload = CSng(Val(CType(dgvDetailed.Item(3, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))
            ISPOffpeakDownload = CSng(Val(CType(dgvDetailed.Item(6, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))
            ISPOffpeakUpload = CSng(Val(CType(dgvDetailed.Item(7, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))

            'write values back
            CType(dgvDetailed.Item(2, e.RowIndex), DataGridViewTextBoxCell).Value = ISPPeakDownload.ToString & " MB"
            CType(dgvDetailed.Item(3, e.RowIndex), DataGridViewTextBoxCell).Value = ISPPeakUpload.ToString & " MB"
            CType(dgvDetailed.Item(6, e.RowIndex), DataGridViewTextBoxCell).Value = ISPOffpeakDownload.ToString & " MB"
            CType(dgvDetailed.Item(7, e.RowIndex), DataGridViewTextBoxCell).Value = ISPOffpeakUpload.ToString & " MB"

            'either on or off Peak
            If dgvDetailed.Item(4, e.RowIndex).Value.ToString = "-" Then
                'Offpeak
                NICDownload = CSng(Val(CType(dgvDetailed.Item(8, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))
                NICUpload = CSng(Val(CType(dgvDetailed.Item(9, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))

                'write value back
                CType(dgvDetailed.Item(8, e.RowIndex), DataGridViewTextBoxCell).Value = NICDownload.ToString & " MB"
                CType(dgvDetailed.Item(9, e.RowIndex), DataGridViewTextBoxCell).Value = NICUpload.ToString & " MB"
            Else
                'Peak
                NICDownload = CSng(Val(CType(dgvDetailed.Item(4, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))
                NICUpload = CSng(Val(CType(dgvDetailed.Item(5, e.RowIndex), DataGridViewTextBoxCell).Value.ToString))

                'write value back
                CType(dgvDetailed.Item(4, e.RowIndex), DataGridViewTextBoxCell).Value = NICDownload.ToString & " MB"
                CType(dgvDetailed.Item(5, e.RowIndex), DataGridViewTextBoxCell).Value = NICUpload.ToString & " MB"
            End If

            '########################################3

            Dim fsLog As New IO.FileStream(AppDataPath & "usageagent.log", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite)
            Dim wLog As New IO.BinaryWriter(fsLog)

            'jump to record
            fsLog.Seek(-54 * UsageID, IO.SeekOrigin.End)

            'jump foward to edit field
            fsLog.Seek(14, IO.SeekOrigin.Current)

            'write ISPPeakDownload
            wLog.Write(ISPPeakDownload)
            wLog.Write(ISPPeakUpload)
            wLog.Write(ISPOffpeakDownload)
            wLog.Write(ISPOffpeakUpload)

            'jump foward to edit field
            fsLog.Seek(16, IO.SeekOrigin.Current)

            Dim DownloadChange As Single
            Dim UploadChange As Single

            If NICDownload = 0 Then
                DownloadChange = 0
            Else
                DownloadChange = CSng(Format(NICDownload * 1024, "#.##"))
            End If
            wLog.Write(DownloadChange)

            If NICUpload = 0 Then
                UploadChange = 0
            Else
                UploadChange = CSng(Format(NICUpload * 1024, "#.##"))
            End If
            wLog.Write(UploadChange)

            wLog.Close()
            fsLog.Close()

            RefreshDetailed()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Usage Agent", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

End Class
